package com.yds.baseproject_java;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.yds.socket.CodeType;
import com.yds.socket.bean.OtherMsgBean;
import com.yds.socket.client.ClientCallback;
import com.yds.socket.client.SocketClient;
import com.yds.socket.server.ServerCallback;
import com.yds.socket.server.SocketServer;
import com.yds.socket.utils.SocketBytesUtil;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private SocketServer mSocketServer;
    private SocketClient mSocketClient;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSocketServer = new SocketServer();
        mSocketClient = new SocketClient();

        findViewById(R.id.mButtonServerOpen).setOnClickListener(view -> {
            openServer();
        });

        findViewById(R.id.mButtonServerClose).setOnClickListener(view -> {
            closeServer();
        });

        findViewById(R.id.mButtonServerSend).setOnClickListener(view -> {
            mSocketServer.sendMsgToClient("服务端-发送数据");
        });

        findViewById(R.id.mButtonConnectServer).setOnClickListener(view -> {
            connectServer();
        });

        findViewById(R.id.mButtonDisconnectServer).setOnClickListener(view -> {
            disconnectServer();
        });

        findViewById(R.id.mButtonClientSend).setOnClickListener(view -> {
            mSocketClient.sendMsgToServer("客户端-发送数据");
        });

        checkPermission();
    }

    /* 开启服务端 */
    private void openServer() {
        mSocketServer.startSocketServer(6688, new ServerCallback() {
            @Override
            public void receiveClientMsg(boolean state, byte[] buffers) {
                String msg = SocketBytesUtil.convertBytesToString(buffers);
                Log.d("YDSimon", "receiveClientMsg = " + msg);
                if (TextUtils.isEmpty(msg)) return;
                String result = msg.toUpperCase();
                // 虹膜
                Log.d("YDSimon", "虹膜 = " + SocketBytesUtil.hexToDecimal(result.substring(2, 6)));

                // 甲烷
//                Log.d("YDSimon", "甲烷 = " + result.substring(6, 6 + 8) + " - " + initFloat(IEEE754.hexStr2FloatIeee(result.substring(6, 6 + 8))));
                // 氧气
//                Log.d("YDSimon", "氧气 = " + result.substring(22, 22 + 8) + " - " + initFloat(IEEE754.hexStr2FloatIeee(result.substring(22, 22 + 8))));
                // 一氧化碳
//                Log.d("YDSimon", "一氧化碳 = " + result.substring(30, 30 + 8) + " - " + initFloat(IEEE754.hexStr2FloatIeee(result.substring(30, 30 + 8))));
                // 二氧化碳
//                Log.d("YDSimon", "二氧化碳 = " + result.substring(54, 54 + 8) + " - " + initFloat(IEEE754.hexStr2FloatIeee(result.substring(54, 54 + 8))));
            }

            @Override
            public void otherMsg(OtherMsgBean otherMsgBean) {
                switch (otherMsgBean.code) {
                    case CodeType.DISCONNECT_SOCKET:
                        Log.d("YDSimon", "otherMsg DISCONNECT_SOCKET = " + otherMsgBean.toString());
                        break;
                    case CodeType.CONNECT_SOCKET:
                        Log.d("YDSimon", "otherMsg CONNECT_SOCKET = " + otherMsgBean.toString());
                        break;
                    case CodeType.SUCCESS_MSG:
                        Log.d("YDSimon", "otherMsg SUCCESS_MSG = " + otherMsgBean.toString());
                        break;
                    case CodeType.ERROR_MSG:
                        Log.d("YDSimon", "otherMsg ERROR_MSG = " + otherMsgBean.toString());
                        break;
                    case CodeType.EXCEPTION_MSG:
                        Log.d("YDSimon", "otherMsg EXCEPTION_MSG = " + otherMsgBean.toString());
                        break;
                }
            }

        });
    }

    /* 关闭服务端 */
    private void closeServer() {
        mSocketServer.stopSocketServer();
    }

    /* 连接服务端 */
    private void connectServer() {
//        mSocketClient.connectSocketServer("192.168.113.49", 6688, new ClientCallback() {
        mSocketClient.connectSocketServer("192.168.110.234", 6688, new ClientCallback() {
            @Override
            public void receiveServerMsg(boolean state, byte[] buffers) {
                String msg = SocketBytesUtil.convertBytesToString(buffers);
                Log.d("YDSimon", "receiveServerMsg = " + msg);
                // 虹膜
                Log.d("YDSimon", "虹膜 = " + SocketBytesUtil.hexToDecimal(msg.substring(2, 6)));
            }

            @Override

            public void otherMsg(OtherMsgBean otherMsgBean) {
                Log.d("YDSimon", "otherMsg = " + otherMsgBean.toString());
            }
        });
    }

    /* 断开连接服务端 */
    private void disconnectServer() {
        mSocketClient.disconnectSocketServer();
    }

    private void checkPermission() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 已经拥有权限，执行相应操作

        } else {
            // 没有权限，请求权限
            EasyPermissions.requestPermissions(this, "需要相机权限", 100, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // 已经拥有权限，执行相应操作

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // 权限被拒绝
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("YDSimon", "onActivityResult requestCode = " + requestCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发给 EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}